package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kabuda
 * @create 2022-08-24 16:32
 */
public class SpringSecurityUserService  implements UserDetailsService {

    //模拟数据库中的用户数据
    public  static Map<String, User> map = new HashMap<>();
    static {
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("admin");

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword("1234");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据库获得用户信息（包含数据库存储的密码信息）
        //此处我们使用模拟数据
        User user = map.get(username);
        if(user!=null){
            List<GrantedAuthority> list = new ArrayList();
            //权限和角色后续都是从数据库查询，此处先不
            //设置权限
            list.add(new SimpleGrantedAuthority("permission_A"));
            list.add(new SimpleGrantedAuthority("permission_B"));
            //设置只有admin有admin角色，小明没有
            if(username.equals("admin")){
                //设置角色
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
            //将用户信息返回给框架
            org.springframework.security.core.userdetails.User securityUser =
                    new org.springframework.security.core.userdetails.User(username,"{noop}"+user.getPassword(),list);
            //框架会自己进行比对(页面密码和数据库存储的密码)
            return securityUser;
        }else{
            return null;
        }
    }
}
